package com.mobile.struts.action;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.criterion.Order;

import com.mobile.business.tree.ITreeBaseBusiness;
import com.mobile.model.TreeBasePojo;
import com.mobile.struts.action.tools.ClassDelegate;
import com.mobile.struts.action.tools.TreeJsObject;
import com.mobile.tools.BeanUtil;
import com.mobile.tools.JsonHelp;

public class TreeBaseAction extends BaseDispatchAction{
	
	private ITreeBaseBusiness getTreeBusinessBean(){
		return (ITreeBaseBusiness)getWac().getBean(ITreeBaseBusiness.BEAN_ID);
	}

	/**
	 * 获取树节点
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward treeNode(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		
		String uniqueCode=request.getParameter("uniqueCode");
		
		String node=request.getParameter("node");
		//要实例化的model类
		String clazz = request.getParameter("clazz");
		List<TreeBasePojo> list=new ArrayList<TreeBasePojo>();		
		
		PrintWriter out=null;
		try {
			if(node==null||clazz== null){
				return null;
			}else{
				//list=getMainMenuBusiness().findByFatherMenu(node);
				clazz=ClassDelegate.clazzMap.get(clazz);
				Map<String,Object> map = new HashMap<String,Object>();
				//绑定树节点的父节点信息为parentId
				map.put("parentId", node);
				
				Object pojo=Class.forName(clazz).newInstance();
				BeanUtils.populate(pojo, map);
				list = getTreeBusinessBean().findByExample(pojo, new String[]{"isLeafNode","serialNumber"});
			}
			
			out=response.getWriter();
			Enumeration enu=request.getParameterNames();
			StringBuffer content=new StringBuffer();
			content.append("[");
			int i=1;
			int length=list.size();
			for(TreeBasePojo tree:list){				
				content.append("{");
				content.append("id:'"+tree.getUniqueCode()+"',");
				content.append("text:'"+tree.getText()+"',");
				String icon = tree.getIcon();
				if(icon!=null){
					content.append("icon:'"+icon+"',");
				}				
				if("0".equals(tree.getIsLeafNode())){
					content.append("leaf:false");					
				}else{
					content.append("leaf:true");
				}
				if(i!=length){
					content.append("},");
				}else{
					content.append("}");
				}
				i++;
			}
			content.append("]");
			out.println(content);
		} catch(Exception e){
			log.error(e);
		}finally{		
			out.close();
		}
		return null;
	} 
	/**
	 * 通过JsObject来获取树节点<br>
	 * 在Parameter中传递node、nodeName、clazz、jsObject、orders<br>
	 * node	: 节点的id值<br>
	 * nodeName : 映射到clazz 类中的属性名
	 * clazz : 读取树的类
	 * jsObject : 读取的类映射到js中的信息
	 * order : 节点排序的js对象字符串{ascending:true,propertyName:''}
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward treeNodeByJsObject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		
		String uniqueCode=request.getParameter("uniqueCode");
		//node信息，nodeName为映射到clazz中的属性名
		String node=request.getParameter("node");
		String nodeName = request.getParameter("nodeName");
		//要实例化的model类
		String clazz = request.getParameter("clazz");
		List list=new ArrayList();		
		
		//获取jsObject字符串
		String jsObjectString = request.getParameter("jsObject");
		TreeJsObject treeJsObject = new TreeJsObject();
		JsonHelp jsonHelp =new JsonHelp();
		//把jsObject字符串解析成treeJsObject
		jsonHelp.parseJson(jsObjectString, treeJsObject);
		
		String order = request.getParameter("order");
		
		
		
		PrintWriter out=null;
		try {
			if(node==null||clazz== null){
				return null;
			}else{
				//list=getMainMenuBusiness().findByFatherMenu(node);
				clazz=ClassDelegate.clazzMap.get(clazz);
				//设置treeJsObject的clazz属性
				treeJsObject.setClazz(Class.forName(clazz));
				Object pojo=Class.forName(clazz).newInstance();
				if(nodeName!=null){
					Map<String,Object> map = new HashMap<String,Object>();
					//绑定树节点的父节点信息为parentId
					map.put(nodeName, node);
									
					BeanUtils.populate(pojo, map);
				}
				//排序信息
				List<Order> listOrder = new ArrayList();
				if(order!=null){
					listOrder =jsonHelp.parseJsonArray(order, Order.class);
				}
				  
				
				list = getTreeBusinessBean().findByExample(pojo, listOrder);
			}
			
			out=response.getWriter();
			Enumeration enu=request.getParameterNames();
			StringBuffer content=new StringBuffer();
			content.append("[");
			int i=1;
			int length=list.size();
			Map<String,PropertyDescriptor> map = treeJsObject.getPropertyDescriptors(Class.forName(clazz));
			for(Object obj:list){		
				TreeBasePojo tree = treeJsObject.getTreeBasePojo(obj);
				content.append("{");
				content.append("id:'"+tree.getUniqueCode()+"',");
				content.append("text:'"+tree.getText()+"',");
				String icon = tree.getIcon();
				if(icon!=null){
					content.append("icon:'"+icon+"',");
				}				
				if("0".equals(tree.getIsLeafNode())){
					content.append("leaf:false");					
				}else{
					content.append("leaf:true");
				}
				if(i!=length){
					content.append("},");
				}else{
					content.append("}");
				}
				i++;
			}
			content.append("]");
			out.println(content);
		} catch(Exception e){
			e.printStackTrace();
			log.error(e);
		}finally{		
			out.close();
		}
		return null;
	} 
	/**
	 * 发送数据到后台并保存
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return		
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String deptId="deptId";
		String userId="userId";
		
		String uniqueCode=request.getParameter("uniqueCode");
		
		String parentId=request.getParameter("parentId");
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);

		try {
			Object pojo=Class.forName(clazz).newInstance();
			//BeanUtils.populate(pojo, request.getParameterMap());
			BeanUtil.copyPropertiesClearWhite(pojo, request.getParameterMap());
			
			if(parentId!=null&&!"".equals(parentId)){
				Map<String,Object> map = new HashMap<String,Object>();
				//绑定树节点的父节点信息为parentId
				map.put("parentId", parentId);
				BeanUtils.populate(pojo, map);
			}
			
			if(uniqueCode==null||"".equals(uniqueCode)){
				//读取父节点
				Object fatherNode=getTreeBusinessBean().get(Class.forName(clazz), parentId);
				
				Map<String,Object> map =new HashMap<String,Object>();
				map.put("isLeafNode", 0);
				
				BeanUtils.populate(fatherNode, map);
				
				List list=new ArrayList();
				list.add(pojo);
				list.add(fatherNode);
				
				getTreeBusinessBean().mergeCollection(list);
			}else{
				getTreeBusinessBean().mergeNotNull(uniqueCode,pojo);
			}
		} catch(Exception e){
			PrintWriter out=null;
			try {				
				out=response.getWriter();
				out.println(JsonHelp.getFormFailJson("保存数据失败！"));
				log.error(e);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} finally{
				out.close();
			}
		}
		return null;	
	}
	/**
	 * 当树节点改变顺序是调用此函数
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return		
	 */
	public ActionForward sort(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String deptId="deptId";
		String userId="userId";
		
		String uniqueCode=request.getParameter("uniqueCode");
		
		String fatherUniqueCode=request.getParameter("fatherUniqueCode");
		
		String clazz = request.getParameter("clazz");
		clazz = ClassDelegate.clazzMap.get(clazz);
		
		
		String data = request.getParameter("data");
		
		
		try {
			getTreeBusinessBean()
				.saveSort(data,Class.forName(clazz));		
			//getTreeBusinessBean().merge(pojo);
		} catch(Exception e){
			e.printStackTrace();
			PrintWriter out=null;
			try {				
				out=response.getWriter();
				out.println(JsonHelp.getFormFailJson("操作失败，请联系管理员！"));
				log.error(e);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} finally{
				out.close();
			}
		}
		return null;	
	}
}
